#pragma once
#include <iostream>
#include <cstring>
#include <cerrno>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <pthread.h>
#include <functional>
#include "Addr.hpp"
#include "Thread.hpp"
class UdpClient
{
public:
    UdpClient()
        :_t(ThreadData("recv"), std::bind(&UdpClient::Recv, this, std::placeholders::_1))
    {}
    ~UdpClient()
    {
        close(_sockfd);
        _t.Join();
    }
    void Init()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        {
            std::cout << "socket failed, errno : " << strerror(errno) << std::endl;
            exit(0);
        }
        std::cout << "socket success, _sockfd : " << _sockfd << std::endl;
    }
    void Recv(ThreadData td)
    {
        char buffer[1024];
        while(1)
        {
            struct sockaddr_in tmp;
            socklen_t sz = sizeof(tmp);
            int n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&tmp, &sz);
            if(n > 0)
            {
                buffer[n] = 0;
                std::cout << "[" << Addr::GetInstance()->ip_port(tmp) << "]# " << buffer << std::endl;
            }
            else if(n == 0)
            {
                std::cout << "退出" << std::endl;
                break;
            }
            else
            {
                std::cout << "recvfrom failed, error: " << strerror(errno) << std::endl;
                break;
            }
        }
    }
    void Start(struct sockaddr_in server)
    {
        _t.Start();
        // int n = bind(_sockfd, (struct sockaddr*)&server, sizeof(server)); // 不需要手动绑定，OS会帮我们做
        std::string message;
        char buffer[1024];
        while(1)
        {
            std::cout << "enter # ";
            std::getline(std::cin, message);
            int n = sendto(_sockfd, message.c_str(), message.size(), 0, (struct sockaddr*)&server, sizeof(server));
            if(n < 0)
            {
                std::cout << "sendto failed, error: " << strerror(errno) << std::endl;
                break;
            }
        }
    }
private:
    int _sockfd;
    Thread<ThreadData> _t;
    pthread_t _tid;
};